package com.sangeng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.dto.RoleSearchParamsDTO;
import com.sangeng.domain.entity.user.Role;
import com.sangeng.domain.vo.Result;
import com.sangeng.domain.vo.RoleSearchVO;
import com.sangeng.mapper.RoleMapper;
import com.sangeng.service.IRoleService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    /**
     * 根据角色id查询角色名称
     */
    @Override
    public String getRoleNameById(Long roleId) {
        return lambdaQuery().eq(Role::getId, roleId).one().getName();
    }
    /**
     * 分页查询角色信息
     */
    @Override
    public RoleSearchVO pageList(RoleSearchParamsDTO roleSearchParamsDTO) {
        Page<Role> page = new Page<>(roleSearchParamsDTO.getPage(), roleSearchParamsDTO.getLimit());
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(roleSearchParamsDTO.getRoleName())){
            queryWrapper.like(Role::getName, roleSearchParamsDTO.getRoleName());
        }
        if(StrUtil.isNotBlank(roleSearchParamsDTO.getStartTime()) && StrUtil.isNotBlank(roleSearchParamsDTO.getEndTime())){
            queryWrapper.between(Role::getCreateTime,
                    LocalDate.parse(roleSearchParamsDTO.getStartTime()),
                    LocalDate.parse(roleSearchParamsDTO.getEndTime())
                    );
        }
        Page<Role> rolePage = page(page, queryWrapper);
        List<RoleSearchVO.RoleInfo> list = rolePage.getRecords().stream().map(role ->
                BeanUtil.copyProperties(role, RoleSearchVO.RoleInfo.class)
        ).collect(Collectors.toList());
        return new RoleSearchVO(list, rolePage.getTotal());
    }
}
